// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Threading;

namespace TaskbarConcepts
{
    /// <summary>
    /// Interaction logic for FlashingTaskbar.xaml
    /// </summary>
    public partial class FlashingTaskbar : UserControl
    {
        public FlashingTaskbar()
        {
            InitializeComponent();
        }

        public void OnFlashWindow(object unused1, RoutedEventArgs unused2)
        {
            FlashWindowHelper helper = new FlashWindowHelper();
            helper.Flash(6, 400, Application.Current.MainWindow);
        }
    }

    internal sealed class FlashWindowHelper
    {
        DispatcherTimer _timer;
        int _count = 0;
        int _maxTimes = 0;
        Window _window;

        public void Flash(int times, double millliseconds, Window window)
        {
            _timer = new DispatcherTimer();
            _maxTimes = times;
            _timer.Interval = TimeSpan.FromMilliseconds(millliseconds);
            _timer.Tick += OnTick;
            _window = window;
            _timer.Start();
        }

        void OnTick(object sender, EventArgs e)
        {
            if (++_count < _maxTimes)
            {
                Win32.FlashWindow(new WindowInteropHelper(_window).Handle, (_count % 2) == 0);
            }
            else
            {
                _timer.Stop();
            }
        }
    }

    internal static class Win32
    {
        [DllImport("user32.dll")]
        public static extern bool FlashWindow(IntPtr hwnd, bool bInvert);
    }
}